import { Button, Card, Checkbox, Form, message, Modal, Radio, Row, Col, Select, Input, InputNumber, DatePicker, Transfer, Table, Spin} from "antd";
import DescriptionList from '@/components/DescriptionList';
import { connect } from "dva";
import React, { PureComponent } from "react";
import { transferOption } from "@/utils/common";
import { getDicByKey } from '@/support/common';
import moment from 'moment';
import PropTypes from 'prop-types';
import Ellipsis from '@/components/Ellipsis';
import difference from 'lodash/difference';

export const repositoryHash = {
  '0': '主库',
  '1': '二库',
  '2': '二网',
};
const FormItem = Form.Item;
const { Description } = DescriptionList;
const TableTransfer = ({ leftColumns, rightColumns, loading, ...restProps }) => (
  <Transfer {...restProps} showSelectAll={false}>
    {({
      direction,
      searchPlaceholder,
      filteredItems,
      onItemSelectAll,
      onItemSelect,
      selectedKeys: listSelectedKeys,
      disabled: listDisabled,
    }) => {
      const columns = direction === 'left' ? leftColumns : rightColumns;

      const rowSelection = {
        getCheckboxProps: (item) => ({
          disabled: listDisabled || item.disabled,
        }),
        onSelectAll(selected, selectedRows) {
          const treeSelectedKeys = selectedRows
            .filter((item) => !item.disabled)
            .map(({ key }) => key);
          const diffKeys = selected
            ? difference(treeSelectedKeys, listSelectedKeys)
            : difference(listSelectedKeys, treeSelectedKeys);
          onItemSelectAll(diffKeys, selected);
        },
        onSelect({ key }, selected) {
          onItemSelect(key, selected);
        },
        selectedRowKeys: listSelectedKeys,
      };

      return (
        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={filteredItems}
          size="small"
          style={{ pointerEvents: listDisabled ? 'none' : null }}
          rowClassName={(record) => {
            return record.disabled ? styles['disabled-row'] : '';
          }}
          onRow={({ key, disabled: itemDisabled }) => ({
            onClick: () => {
              if (itemDisabled || listDisabled) return;
              onItemSelect(key, !listSelectedKeys.includes(key));
            },
          })}
          pagination={false}
          scroll={{ y: 220 }}
          loading={loading}
        />
      );
    }}
  </Transfer>
);
const leftTableColumns = [
  {
    dataIndex: 'vin',
    title: 'VIN',
  },
  {
    dataIndex: 'repository',
    title: '围栏所属仓库',
    render: (val) => (
      <Ellipsis length={12} tooltip>
        {repositoryHash[val] || ''}
      </Ellipsis>
    ),
  },
  {
    dataIndex: 'fenceName',
    title: '围栏名称',
    render: (val) => (
      <Ellipsis length={12} tooltip>
        {val}
      </Ellipsis>
    ),
  },
];
const rightTableColumns = [
  {
    dataIndex: 'vin',
    title: 'VIN',
  },
  {
    dataIndex: 'repository',
    title: '围栏所属仓库',
    render: (val) => (
      <Ellipsis length={12} tooltip>
        {repositoryHash[val] || ''}
      </Ellipsis>
    ),
  },
  {
    dataIndex: 'fenceName',
    title: '围栏名称',
    render: (val) => (
      <Ellipsis length={12} tooltip>
        {val}
      </Ellipsis>
    ),
  },
];


@connect((state) => ({
  menu: state.menu,
  creditCar: state.creditCar,
}))
export default class lockListModal extends PureComponent {
  static contextTypes = {
    dicData: PropTypes.any,
  };
  state = {
    originData: [],
    targetKeys: [],
    unlockCount: 0,
    lockCount: 0,
    limitNum: 0,
    dataLoading: false,
    buttonLoading: false,
    limitUuid:'',
  };
  componentDidMount() {
    this.getData();
  }
  getData = ()=>{
    const { dealerLimitData } = this.props;
    this.setState({
      dataLoading: true,
    });
    const params = {
      uuid: dealerLimitData.uuid,
      orgId: dealerLimitData.orgId,
      dealerCode: dealerLimitData.dealerCode,
      limitValue: dealerLimitData.limitValue
    }
    this.props.dispatch({
      type: 'creditCar/postObjWithRes',
      payload: {
        url: '/riskSeller/vehicle/list', 
        ...params,
      },
      callback: (res) => {
        if(res.statusCode == '0') {
          const data = res.data;
            let dataSource = [];
            dataSource = dataSource.concat(data.lockedList);
            dataSource = dataSource.concat(data.unlockList);
            this.setState({
              originData: dataSource?.map((item) => {
                return {
                  ...item,
                  key: item.vin,
                };
              }),
              targetKeys: data.lockedList?.map((item) =>{
                return item.vin
              }),
              unlockCount: data.unlockList?.length,
              lockCount:  data.lockedList?.length,
              limitNum: data.limitNum,
              limitUuid: data.limitUuid,
            });
        }
        this.setState({
          dataLoading: false,
        });
      },
    })
  }
  setLoading = (flag) => {
    this.setState({
      buttonLoading: flag,
    });
  };

  close = () => {
    const { changeriskLogModalVisible} = this.props;
    this.setState({
      buttonLoading: false,
      originData: [],
      targetKeys: [],
      unlockCount: 0,
      lockCount: 0,
      limitNum: 0,
      limitUuid:'',
    });
    changeriskLogModalVisible(false)
  };

  ok = (e) => {
    e.preventDefault();
    const {targetKeys} = this.state;
    const { dispatch,dealerLimitData,changeriskLogModalVisible } = this.props;
    this.setLoading(true);
    let params = {};
    params.lockedList = targetKeys; 
    params.uuid = this.state.limitUuid;
    dispatch({
      type: 'creditCar/postObjWithRes',
      payload: { url: '/riskSeller/vehicle/lock/save', ...params },
      callback: response => {
        if (response.statusCode === "0") {
          message.success("操作成功");
          this.setState({
            originData: [],
            targetKeys: [],
            unlockCount: 0,
            lockCount: 0,
            limitNum: 0,
            limitUuid:'',
          });
          changeriskLogModalVisible(false)
        } else {
        }
        this.setLoading(false);
      }
    });
   
  };

  onTransferChange = (nextTargetKeys) => {
    const { originData} = this.state;
    this.setState({ 
      targetKeys: nextTargetKeys,
      unlockCount: originData.length - nextTargetKeys.length, 
      lockCount: nextTargetKeys.length,
     });
  };
 
  renderSimpleForm() {
    const { modalVisible, dealerLimitData,changeriskLogModalVisible} = this.props;
    const {originData, targetKeys, unlockCount, lockCount, dataLoading, limitNum, buttonLoading,} = this.state;
    const footer = (
      <div>
        <Button onClick={this.close}>取消</Button>
        <Button loading={buttonLoading} onClick={this.ok} type="primary">确定</Button>
      </div>
    );
  
    return (
      <Modal
        footer={footer}
        title="锁车清单"
        onCancel={() => changeriskLogModalVisible(false)}
        visible={true}
        width="82%"
      >
        <Spin
           spinning={dataLoading}
           size="large"
        >
       <div>
          <Card bordered={false}>
           <Row gutter={24}>
            <div style={{paddingBottom: '50px', width: '100%'}}>
            <DescriptionList span={2}>
            <Description term="经销商名称" >
                <Ellipsis length={10} tooltip>
                {dealerLimitData.dealerName || ''}
                </Ellipsis>
              </Description>
              <Description term="额度（台）">
               {limitNum}
              </Description>
            </DescriptionList>
            </div>
           </Row>
           <Row gutter={24}>
           <TableTransfer
           dataSource={originData}
           titles={['未锁车辆总数:' + unlockCount, '锁车数量:' + lockCount]}
           operations={['锁车', '解锁']}
           notFoundContent="列表为空"
           targetKeys={targetKeys}
           showSearch
           searchPlaceholder="请输入"
           onChange={this.onTransferChange}
           filterOption={(inputValue, item) => item.vin.indexOf(inputValue) !== -1}
           leftColumns={leftTableColumns}
           rightColumns={rightTableColumns}
           loading={dataLoading}
           listStyle={{
             minWidth: 380,
           }}
          />
           </Row>
          </Card>
        </div>
         <div style={{ color: 'red', marginTop: 10, fontSize: 'small' }}>
            <div>注:</div>
            <div>1、新发运的授信车，会入库即锁</div>
            <div>2、库存的授信车，会按额度锁车</div>
          </div>
        </Spin>
      </Modal>
    );
  }

  render() {
    return this.renderSimpleForm();
  }
}
